package com.aiguigu.lottery.prize.mapper;

import com.aiguigu.lottery.common.entity.PrizeEntity;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface PrizeMapper {
    
    /**
     * 插入奖品
     */
    @Insert("INSERT INTO prize (name, image_url, probability, total, remaining, status, created_by, create_time, update_time) " +
            "VALUES (#{name}, #{imageUrl}, #{probability}, #{total}, #{remaining}, #{status}, #{createdBy}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(PrizeEntity prize);
    
    /**
     * 根据ID更新奖品
     */
    @Update("UPDATE prize SET name = #{name}, image_url = #{imageUrl}, probability = #{probability}, " +
            "total = #{total}, remaining = #{remaining}, status = #{status}, update_time = #{updateTime} WHERE id = #{id}")
    int updateById(PrizeEntity prize);
    
    /**
     * 根据ID删除奖品
     */
    @Delete("DELETE FROM prize WHERE id = #{id}")
    int deleteById(@Param("id") Integer id);
    
    /**
     * 根据ID查询奖品
     */
    @Select("SELECT * FROM prize WHERE id = #{id}")
    PrizeEntity findById(@Param("id") Integer id);
    
    /**
     * 查询所有启用的奖品
     */
    @Select("SELECT * FROM prize WHERE status = 1 ORDER BY probability DESC")
    List<PrizeEntity> findAllEnabled();
    
    /**
     * 查询所有奖品
     */
    @Select("SELECT * FROM prize ORDER BY create_time DESC")
    List<PrizeEntity> findAll();
    
    /**
     * 根据创建者查询奖品
     */
    @Select("SELECT * FROM prize WHERE created_by = #{createdBy} ORDER BY create_time DESC")
    List<PrizeEntity> findByCreatedBy(@Param("createdBy") Integer createdBy);
    
    /**
     * 更新奖品状态
     */
    @Update("UPDATE prize SET status = #{status}, update_time = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Integer id, @Param("status") Integer status);
    
    /**
     * 验证奖品创建者权限
     */
    @Select("SELECT COUNT(*) FROM prize p JOIN emp e ON p.created_by = e.id WHERE p.id = #{prizeId} AND e.job = 1")
    int validateCreatorPermission(@Param("prizeId") Integer prizeId);
    
    /**
     * 减少奖品库存（原子操作）
     */
    @Update("UPDATE prize SET remaining = remaining - 1, update_time = NOW() " +
            "WHERE id = #{prizeId} AND remaining > 0 AND status = 1")
    int decreaseStock(@Param("prizeId") Integer prizeId);
    
    /**
     * 检查奖品库存
     */
    @Select("SELECT remaining FROM prize WHERE id = #{prizeId} AND status = 1")
    Integer checkStock(@Param("prizeId") Integer prizeId);
    
    /**
     * 查询有库存的启用奖品
     */
    @Select("SELECT * FROM prize WHERE status = 1 AND remaining > 0 ORDER BY probability DESC")
    List<PrizeEntity> findAvailablePrizes();
    
    /**
     * 批量更新奖品库存
     */
    @Update("UPDATE prize SET total = #{total}, remaining = #{remaining}, update_time = NOW() WHERE id = #{id}")
    int updateStock(@Param("id") Integer id, @Param("total") Integer total, @Param("remaining") Integer remaining);
}